package com.changdu.seatunnel.admin.pojo;

import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

import lombok.Data;

@Data
public class CopySyncConfigGenerate {
	
    private String sourceDataCenter;
    private String sourceInstance;
    
    // 替换规则 (.*)_en -> $1_fr
    private ReplaceRegex sourceDbReplaceRegex;
    private ReplaceRegex sourceTbReplaceRegex;
    
    private String targetDataCenter;
    private String targetInstance;
    
    // 替换规则
    private ReplaceRegex targetDbReplaceRegex;
    private ReplaceRegex targetTbReplaceRegex;
    
    // 默认值
    private List<DefaultValue> defaultValues;
    
    // 绑定主题
    private KafkaConfig kafkaConfig;
    
	public void setSourceDbReplaceRegex(String sourceDbReplaceRegex) {
		this.sourceDbReplaceRegex = StringUtils.isNoneEmpty(sourceDbReplaceRegex)
				? ReplaceRegex.create(sourceDbReplaceRegex)
				: null;
	}
	
	public void setSourceTbReplaceRegex(String sourceTbReplaceRegex) {
		this.sourceTbReplaceRegex = StringUtils.isNoneEmpty(sourceTbReplaceRegex)
				? ReplaceRegex.create(sourceTbReplaceRegex)
				: null;
	}
	
	public void setTargetDbReplaceRegex(String targetDbReplaceRegex) {
		this.targetDbReplaceRegex = StringUtils.isNoneEmpty(targetDbReplaceRegex)
				? ReplaceRegex.create(targetDbReplaceRegex)
				: null;
	}
	
	public void setTargetTbReplaceRegex(String targetTbReplaceRegex) {
		this.targetTbReplaceRegex = StringUtils.isNoneEmpty(targetTbReplaceRegex)
				? ReplaceRegex.create(targetTbReplaceRegex)
				: null;
	}
	
	// (.*)_en -> $1_fr
	@Data
	public static class ReplaceRegex {
		
		public static ReplaceRegex create(String replaceRegex) {
			String[] args = replaceRegex.split("->", 2);
			
			if (args.length != 2)
				throw new IllegalArgumentException("正则表达式错误");
				
			ReplaceRegex regex = new ReplaceRegex();
			regex.setRegex(args[0].trim());
			regex.setValue(args[1].trim());
			return regex;
		}

		private String regex;
		
		private String value;
		
	}
	
	@Data
	public static class DefaultValue {
		
		private String fieldName;
		
		private String defaultValue;
		
	}
	
    public void setKafkaConfig(KafkaConfig kafkaConfig) {
    	if (Objects.isNull(kafkaConfig)) return;
    	
    	if (StringUtils.isNotEmpty(kafkaConfig.getKafkaTopic())) {
    		if (Objects.isNull(kafkaConfig.getKafkaPartition())) {
    			kafkaConfig.setKafkaPartition(3);
    		}
    		this.kafkaConfig = kafkaConfig;
    	}
    }
    
    public boolean kafkaConfigIsEmpty() {
    	return Objects.isNull(kafkaConfig) || StringUtils.isBlank(kafkaConfig.getKafkaTopic());
    }  
    
} 